package com.my.socket.bio.v6;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * Created by ZhongGang
 * at 2018/6/28 16:36
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private String host;
    private int port;
    private ServerSocket serverSocket;

    public Server(String host, int port) throws Exception {
        this.host = host;
        this.port = port;

        this.serverSocket = new ServerSocket();
        this.serverSocket.bind(new InetSocketAddress(this.host, this.port));
    }

    public void startup() throws Exception {
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Socket socket;
                        while ((socket = serverSocket.accept()) != null) {
                            LOGGER.info("thead: {}, incoming connection: {}", Thread.currentThread().getName(), socket);
                        }
                    } catch (Exception e) {
                        LOGGER.error("exception caught, the error is {}", e.getMessage());
                    }
                }
            }, "accepter-thread-" + i).start();
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.startup();

        LOGGER.info("server startup at port {}", server.port);
    }

}
